<template>
  <el-dialog v-model="visible" title="应用版本设置" width="60%">
    <el-form :model="dataForm" :rules="dataRule" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()"
             label-width="120px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="标题" prop="title">
            <el-input v-model="dataForm.title" placeholder="标题" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="版本号" prop="version">
            <el-input v-model="dataForm.version" placeholder="版本号" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="下载地址" prop="url">
            <el-input v-model="dataForm.url" placeholder="下载地址" clearable></el-input>
          </el-form-item>
        </el-col>
        <!--        <el-col :span="12">-->
        <!--          <el-form-item label="应用平台" prop="alarmLevel">-->
        <!--            <ren-select v-model="dataForm.platform" dict-type="kx_img_alarm_level"-->
        <!--                        placeholder="报警等级"></ren-select>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="更新内容" prop="contents">
            <el-input
              v-model="dataForm.contents"
              maxlength="300"
              placeholder="更新内容"
              show-word-limit
              type="textarea"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template v-slot:footer>
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import useView from "@/hooks/useView";
import {IObject} from "@/types/interface";
import baseService from "@/service/baseService";
import {defineComponent, reactive, toRefs} from "vue";
import {getToken} from "@/utils/cache";
import app from "@/constants/app";


function compareVersions(a: any, b: any) {
  const aParts = a.split('.').map(Number);
  const bParts = b.split('.').map(Number);
  const maxLength = Math.max(aParts.length, bParts.length);

  for (let i = 0; i < maxLength; i++) {
    const aVal = i < aParts.length ? aParts[i] : 0;
    const bVal = i < bParts.length ? bParts[i] : 0;

    if (aVal > bVal) return 1;
    if (aVal < bVal) return -1;
  }

  return 0;
}

let dataForm = {
  id: null,
  title: "",
  version: "",
  url: "",
  paltform: "",
  contents: ""
};


export default defineComponent({
  setup() {
    const state = reactive({
      visible: false,
      dataForm: JSON.parse(JSON.stringify(dataForm)),
      version: "",
      checked: [],
      timevalue: [],
      id: ""
    });
    return {...useView(state), ...toRefs(state)};
  },
  computed: {
    dataRule(): IObject {
      return {
        title: [{required: true, message: this.$t("validate.required"), trigger: "blur"}],
        version: [{required: true, message: this.$t("validate.required"), trigger: "blur"}],
        url: [{required: true, message: this.$t("validate.required"), trigger: "blur"}],
        contents: [{required: true, message: this.$t("validate.required"), trigger: "blur"}],
        // contents: [{required: true, message: this.$t("validate.required"), trigger: "change blur"}],
      };
    }
  },
  watch: {
    timevalue: {
      handler(val) {
        if (val === null) {
          this.dataForm.excludeStartTime = "";
          this.dataForm.excludeEndTime = "";
        } else {
          this.dataForm.excludeStartTime = val[0];
          this.dataForm.excludeEndTime = val[1];
        }
      },
      deep: true
    }
  },
  methods: {
    init() {
      this.visible = true;
      this.$nextTick(() => {
        this.getVersion();
      });
    },
    // 获取版本详情
    getVersion() {
      baseService.post("/app/getVersion").then((res) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg);
        }
        console.log(res.data)
        if (res.data === null) {
          this.dataForm = JSON.parse(JSON.stringify(dataForm));
        } else {
          this.dataForm = res.data;
          this.version = res.data.version;
        }
        this.dataForm.id = "";
      });
    },
    dataFormSubmitHandle() {
      const regex = /^\d+(\.\d+)+$/;
      this.$refs["dataFormRef"].validate((valid: boolean) => {
        if (!valid) {
          return false;
        }
        if(!regex.test(this.dataForm.version)){
          return this.$message.error(`版本号格式不符规范（格式：1.0.0），请确认后重试！`)
        }
        if (compareVersions(this.version, this.dataForm.version) !== -1) {
          return this.$message.error(`更新后的版本号不能低于【V${this.version}】，请确认后重试！`)
        }
        baseService.post("/KxAppVersion/kxappversion", this.dataForm).then((res) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          this.$message({
            message: this.$t("prompt.success"),
            type: "success",
            duration: 500,
            onClose: () => {
              this.visible = false;
              this.$emit("close", true);
            }
          });
        });
      });
    }
  }
});
</script>
